﻿using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace FantastPlatform.Framework.Common.Serializable
{
    public static class JsonSerializerHelper
    {
        public static TEntity JsonToEntity<TEntity>(string jsonStr)
        {
            using (StringReader sw = new StringReader(jsonStr))
            {
                JsonSerializer serializer = new JsonSerializer
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                };
                using (JsonReader jw = new JsonTextReader(sw))
                {
                    TEntity entity = serializer.Deserialize<TEntity>(jw);
                    return entity;
                }

            }
        }

        public static string EntityToJson(object obj)
        {
            return EntityToJson(obj, null);
        }

        public static string EntityToJson(object obj, string[] exceptMemberName)
        {
            using (StringWriter sw = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
            {
                JsonSerializer serializer = new JsonSerializer
                {
                    
                    NullValueHandling = NullValueHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver = new NHibernateContractResolver(exceptMemberName),
                }; 
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    jw.Formatting = Formatting.Indented;
                    serializer.Serialize(jw, obj);
                }
                return sw.ToString();
            }
        }
    }
}
